package com.wlgc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlgc.dao.UserDao;
import com.wlgc.entity.RestBean;
import com.wlgc.entity.User;
import com.wlgc.service.UpdateUserService;
import com.wlgc.util.RedisCache;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
@Service
public class UpdateUserServiceImpl implements UpdateUserService {
    @Resource
    RedisCache redisCache;
    @Resource
    UserDao dao;
    @Override
    public RestBean updateUser(int id, String username, String password, String email) {
        // 获取原本存在的用户，如果不存在，则提示用户去注册！
        LambdaQueryWrapper<User> oldWrapper = new LambdaQueryWrapper<>();
        oldWrapper.eq(User::getId,id);
        User oldUser = dao.selectOne(oldWrapper);
        if(!oldUser.getEmail().equals(email))
            return new RestBean<>(500,"学号和通知群邮箱不匹配");
        if (oldUser.getUsername().isEmpty())
            return new RestBean<>(500,"该学号未注册，请到注册页面注册！");
        LambdaQueryWrapper<User> newWrapper = new LambdaQueryWrapper<>();
        newWrapper.eq(User::getUsername,username);
        User newUser = dao.selectOne(newWrapper);
        if (newUser==null||newUser.getUsername().equals(oldUser.getUsername()))
        {
            redisCache.deleteObject("login:"+oldUser.getUsername());
            oldUser.setUsername(username);
            oldUser.setPassword(new BCryptPasswordEncoder().encode(password));
            dao.updateById(oldUser);
            return new RestBean<>(200,"修改成功");
        }
        else {
            return new RestBean<>(500,"该用户名已经存在");
        }

    }
}
